import { Flex, Divider, Skeleton } from "antd";
import { useState, useRef, useEffect } from "react";
import { WeiBoCard } from "./WeiBoCard";
import InfiniteScroll from "react-infinite-scroll-component";
import {
  PAGE_SIZE,
  SITES_URL,
  sortByOrder,
  processCurrentPage,
} from "../Common/commonData";

export function WeiBo({ initData }) {
  const hotRankings = useRef(sortByOrder(initData.initHotData?.items) || []);
  const [showHotRankings, setShowHotRankings] = useState([]);

  // 处理动态加载
  const isLoading = useRef(false);
  const scrollContainerRef = useRef(null);
  const cardRef = useRef(null);

  const loaderMoreData = (pageSize = PAGE_SIZE) => {
    if (
      isLoading.current ||
      showHotRankings?.length > hotRankings?.current?.length
    )
      return;
    isLoading.current = true;

    const [currentPage, currentPageSize] = processCurrentPage(
      pageSize,
      hotRankings.current?.length,
      hotRankings.current
    );

    // 获得剩余所有数据
    if (currentPageSize === hotRankings.current?.length) {
      setShowHotRankings(hotRankings.current);
      return;
    }

    setShowHotRankings((prev) =>
      prev.concat(
        hotRankings.current.slice(
          showHotRankings?.length,
          showHotRankings?.length + currentPageSize
        )
      )
    );
    isLoading.current = false;
  };

  // 1. 监听窗口大小变化，并调整容器高度
  useEffect(() => {
    const handleResize = () => {
      if (isLoading.current) return;

      const windowHeight = window.innerHeight;
      const cardHeight = cardRef?.current?.clientHeight || 50;
      const containerHeight = cardHeight * showHotRankings?.length;
      const cardNum =
        Math.ceil((windowHeight - containerHeight) / cardHeight / 10) * 10;
      if (cardNum >= 10 && containerHeight < windowHeight) {
        loaderMoreData(cardNum);
      }
    };

    // 首次加载时执行
    handleResize();

    // 监听窗口变化
    window.addEventListener("resize", handleResize);

    // 组件卸载时移除监听
    return () => {
      window.removeEventListener("resize", handleResize);
    };
    // 依赖 showHotRankings 确保数据更新后重新计算, 依赖isLoading否则会初始加载两次
  }, [isLoading.current, showHotRankings.length]);

  return (
    <div ref={scrollContainerRef}>
      <WeiBoCard
        item={
          Array.isArray(initData.hotRankingsTop) && initData.hotRankingsTop[0]
        }
        style={{
          borderRadius: "0.3rem 0.3rem 0 0",
        }}
        top={true}
      />
      <Divider style={{ margin: "0" }} />

      <InfiniteScroll
        dataLength={showHotRankings.length}
        next={loaderMoreData}
        hasMore={showHotRankings.length < hotRankings.current?.length}
        loader={
          <Skeleton
            avatar
            paragraph={{ rows: 1 }}
            style={{ padding: 12 }}
            active
          />
        }
        endMessage={
          <a target="_blank" href={SITES_URL.xlWeiBo}>
            <Divider plain>查看更多</Divider>
          </a>
        }
        scrollableTarget="scrollableDiv">
        <Flex vertical={true}>
          {showHotRankings.map((v, i) => (
            <div ref={i === 0 ? cardRef : null} key={"热搜" + i}>
              <WeiBoCard
                item={v}
                style={{
                  borderRadius: `${
                    i === showHotRankings.length - 1 && "0 0 0.3rem 0.3rem"
                  }`,
                }}
              />
              <Divider style={{ margin: "0" }} />
            </div>
          ))}
        </Flex>
      </InfiniteScroll>
    </div>
  );
}
